package online.longzipeng.back.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import online.longzipeng.back.common.exception.MessageException;
import online.longzipeng.back.mapper.BillTypeMapper;
import online.longzipeng.back.pojo.entity.BillType;
import online.longzipeng.back.pojo.param.BillTypeQueryParam;
import online.longzipeng.back.pojo.vo.BillTypeVo;
import online.longzipeng.back.service.BillTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lzp
 */
@Service
public class BillTypeServiceImpl implements BillTypeService {

    @Autowired
    private BillTypeMapper billTypeMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(BillType billType) {
        // 参数校验
        if (StrUtil.isBlank(billType.getName())) {
            throw new MessageException("必须填写账单分类的名称！！");
        }
        // 如果没有账单级别，默认取一级
        if (ObjectUtil.isNull(billType.getLevel())) {
            billType.setLevel(1);
        }
        // 校验是否已有该账单分类
        this.billTypeCheckExist(billType.getLevel(), billType.getName());
        // 如果有id，走二次编辑操作
        if (ObjectUtil.isNotNull(billType.getId())) {
            BillType billTypeOld = billTypeMapper.selectOne(Wrappers.<BillType>lambdaQuery().eq(BillType::getId, billType.getId()));
            BeanUtil.copyProperties(billType, billTypeOld);
            billTypeMapper.updateById(billTypeOld);
        } else {
            // 走新增
            billTypeMapper.insert(billType);
        }
    }

    /**
     * 判断当前新增或二次编辑保存的账单是否已经创建过
     *
     * @param level 账单类型的级别
     * @param name  新增或二次编辑的团队名称
     */
    private void billTypeCheckExist(Integer level, String name) {
        BillType billType = billTypeMapper.selectOne(Wrappers.<BillType>lambdaQuery()
                .eq(BillType::getLevel, level)
                .eq(BillType::getName, name));
        if (ObjectUtil.isNotNull(billType)) {
            throw new MessageException("你已经创建过该账单类型！！");
        }
    }

    @Override
    public List<BillTypeVo> list(BillTypeQueryParam param) {
        return billTypeMapper.selectList(Wrappers.<BillType>lambdaQuery()
                        .eq(ObjectUtil.isNotNull(param.getLevel()), BillType::getLevel, param.getLevel())
                        .eq(ObjectUtil.isNotNull(param.getType()), BillType::getType, param.getType())
                        .like(StrUtil.isNotBlank(param.getName()), BillType::getName, param.getName()))
                .stream().map(bt -> {
                    BillTypeVo vo = new BillTypeVo();
                    BeanUtil.copyProperties(bt, vo);
                    return vo;
                }).collect(Collectors.toList());
    }
}
